package com.hans.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.hans.myscanner.entity.ContactEntity;
import com.hans.myscanner.entity.RecordEntity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/17.
 */
public class DBHelper extends SQLiteOpenHelper {


    private  static  DBHelper self;
    public static DBHelper getInstance(Context context){
        if(self==null) return self=new DBHelper(context);
        return self;
    }

    private static  final String DB_NAME="scanner.com.hans.db";
    private static final  int DB_VERSON=2;

    private static  final  String HISTORY_TABLE_NAME="history";
    private static  final  String HISTORY_KEY_ID="_id";
    private static  final  String HISTORY_QR_TYPE="qr_type";
    private static  final  String HISTORY_QR_CONTENT="qr_content";
    private static  final  String HISTORY_QR_FROM="qr_from";
    private static  final  String HISTORY_QR_TIME="qr_time";

    private static final String CREATE_HISTORY_TABLE_SQL=" CREATE TABLE" +HISTORY_TABLE_NAME+"("
            +HISTORY_KEY_ID+"INTEGER PRIMARY KEY AUTOINCREMENT,"
            +HISTORY_QR_TYPE+"TINYINT,"
            +HISTORY_QR_CONTENT+"TEXT,"
            +HISTORY_QR_FROM+"BOOLEN,"
            +HISTORY_QR_TIME+"DATETIME DEFAULT(datetime('now','localtime')))";

    public DBHelper(Context context) {
        super(context,DB_NAME , null,DB_VERSON);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_HISTORY_TABLE_SQL);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS"+HISTORY_TABLE_NAME);
        onCreate(db);//创建表
    }

    private  SQLiteDatabase getDatebase(){
        SQLiteDatabase db=null;
        try {
            db=getWritableDatabase();
        }catch (SQLiteException e){
            Log.e("HansLog","数据库操作失败");
            e.printStackTrace();
        }
        return  db;
    }


    //类似于MAP集合
    public boolean insertRecord(RecordEntity recordEntity){//插入记录
//        //查找query
//        getWritableDatabase().query(HISTORY_TABLE_NAME,);
//        ContentValues 和HashTable类似都是一种存储的机制 但是两者最大的区别就在于，contenvalues只能存储基本类型的数据，
//                  像string，int之类的，不能存储对象这种东西，而HashTable却可以存储对象。
//        在忘数据库中插入数据的时候，首先应该有一个ContentValues的对象所以：
//        ContentValues initialValues = new ContentValues();
//        initialValues.put(key,values);
//        SQLiteDataBase sdb ;
//        sdb.insert(database_name,null,initialValues);
//        插入成功就返回记录的id否则返回-1；

        ContentValues contentValues=new ContentValues();
        if (recordEntity.getId()>0) contentValues.put(HISTORY_KEY_ID,recordEntity.getId());//开始默认ID=0，判断后面数据大于0

        RecordEntity.RECORD_TYPE recordType=recordEntity.getRecordType();
        contentValues.put(HISTORY_QR_TYPE,recordType.getTypeValue());
        if(recordType== RecordEntity.RECORD_TYPE.CONTACT){
            contentValues.put(HISTORY_QR_CONTENT,((ContactEntity)recordEntity.getRecordContent()).toString());
        } else {
            contentValues.put(HISTORY_QR_CONTENT,(String)recordEntity.getRecordContent());
        }
        contentValues.put(HISTORY_QR_FROM,recordEntity.getRecordFrom().getValue());
        contentValues.put(HISTORY_QR_TIME,recordEntity.getRecordTime());
        return getDatebase().insert(HISTORY_TABLE_NAME,null,contentValues)!=-1;//        插入成功就返回记录的id否则返回-1；
    }

//删除记录  delete(String table, String whereClause, String[] whereArgs)
    public void deleteRecord(int recordId){
        getDatebase().delete(HISTORY_TABLE_NAME,HISTORY_KEY_ID+"=",new String[]{recordId+""});
    }

//获得记录
    public List<RecordEntity> getAllRecords(){
        //类似迭代器Cursor
        Cursor cursor=getDatebase().rawQuery("SELECT * FROM"+HISTORY_TABLE_NAME,null);
        List<RecordEntity> recordEntityList=null;
        if (cursor!=null){
            recordEntityList=new ArrayList<>();
            while (cursor.moveToNext()) {
                RecordEntity recordEntity = new RecordEntity();
                recordEntity.setId(cursor.getInt(cursor.getColumnIndex(HISTORY_KEY_ID)));
                RecordEntity.RECORD_TYPE recordType=RecordEntity.RECORD_TYPE.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_QR_TYPE)));
                recordEntity.setRecordType(recordType);
                recordEntity.setRecordContent(cursor.getColumnIndex(HISTORY_QR_CONTENT));
                RecordEntity.RECORD_FROM recordFrom=RecordEntity.RECORD_FROM.parseFromValue(cursor.getInt(cursor.getColumnIndex(HISTORY_QR_TYPE)));
                recordEntity.setRecordFrom(recordFrom);
                String time=cursor.getString(cursor.getColumnIndex(HISTORY_QR_TIME));
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long timeStamp=System.currentTimeMillis();
                try {
                    timeStamp=simpleDateFormat.parse(time).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                recordEntity.setRecordTime(timeStamp);
                recordEntityList.add(recordEntity);
            }
        }
        return recordEntityList;
    }
}
